package com.njwb.Swing.Bill;

import com.njwb.Util.UtilService;
import com.njwb.pojo.Bill;
//许博4221159015
import javax.swing.*;
import java.awt.*;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;

public class BillController {
    private final BillView view;
    private final UtilService service;

    public BillController(BillView view, UtilService service) {
        this.view = view;
        this.service = service;
        initController();
        loadData();
    }

    private void initController() {
        view.searchButton.addActionListener(e -> searchBills());
        view.addButton.addActionListener(e -> new AddBillDialog(
                (Frame) SwingUtilities.getWindowAncestor(view),
                service,
                this::loadData
        ).setVisible(true));

        view.editButton.addActionListener(e -> editBill());
        view.deleteButton.addActionListener(e -> deleteBill());
        view.exportButton.addActionListener(e -> service.exportTableToTxt(view, view.billTable.getModel()));
    }

    private void searchBills() {
        String keyword = view.searchField.getText().trim();
        String paidOption = (String) view.paidBox.getSelectedItem();
        Boolean isPaid = null;
        if ("已付款".equals(paidOption)) isPaid = true;
        else if ("未付款".equals(paidOption)) isPaid = false;
        fillTable(service.getBill(keyword.isEmpty() ? null : keyword, isPaid));
    }

    private void editBill() {
        int selectedRow = view.billTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(view, "请先选择要修改的账单！");
            return;
        }
        Bill bill = new Bill(
                (int) view.billTableModel.getValueAt(selectedRow, 0),
                (String) view.billTableModel.getValueAt(selectedRow, 1),
                (int) view.billTableModel.getValueAt(selectedRow, 2),
                (String) view.billTableModel.getValueAt(selectedRow, 3),
                Double.valueOf(view.billTableModel.getValueAt(selectedRow, 4).toString()),
                "已付款".equals(view.billTableModel.getValueAt(selectedRow, 5)),
                (String) view.billTableModel.getValueAt(selectedRow, 6),
                (String) view.billTableModel.getValueAt(selectedRow, 7),
                Date.valueOf(view.billTableModel.getValueAt(selectedRow, 8).toString())
        );
        new EditBillDialog((Frame) SwingUtilities.getWindowAncestor(view), service, bill, this::loadData)
                .setVisible(true);
    }

    private void deleteBill() {
        int[] selectedRows = view.billTable.getSelectedRows();
        if (selectedRows.length == 0) {
            JOptionPane.showMessageDialog(view, "请先选择要删除的账单！");
            return;
        }
        StringBuilder idsBuilder = new StringBuilder();
        for (int row : selectedRows) idsBuilder.append(view.billTableModel.getValueAt(row, 0)).append(", ");
        String ids = idsBuilder.substring(0, idsBuilder.length() - 2);

        int confirm = JOptionPane.showConfirmDialog(view, "确定要删除以下账单吗？\n" + ids, "确认删除", JOptionPane.YES_NO_OPTION);
        if (confirm == JOptionPane.YES_OPTION) {
            boolean allSuccess = true;
            for (int row : selectedRows) {
                int billId = (int) view.billTableModel.getValueAt(row, 0);
                if (!service.deleteBill(billId)) allSuccess = false;
            }
            JOptionPane.showMessageDialog(view, allSuccess ? "删除成功！" : "部分账单删除失败！", allSuccess ? "提示" : "警告", allSuccess ? JOptionPane.INFORMATION_MESSAGE : JOptionPane.WARNING_MESSAGE);
            loadData();
        }
    }

    private void fillTable(ArrayList<Bill> billList) {
        view.billTableModel.setRowCount(0);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        for (Bill bill : billList) {
            view.billTableModel.addRow(new Object[]{
                    bill.getBill_id(),
                    bill.getProduct_name(),
                    bill.getQuantity(),
                    bill.getUnit(),
                    bill.getAmount(),
                    bill.getIs_paid() ? "已付款" : "未付款",
                    bill.getSupplier_name(),
                    bill.getProduct_description(),
                    bill.getBill_time()!= null ? sdf.format( bill.getBill_time()) : ""
            });
        }
    }

    public void loadData() {
        fillTable(service.getAllBill());
    }
}
